package algorithm.dichotomy.leetcode;

/**
 * @author: 柒月
 * @date: 2025/5/1 下午1:26
 * @version: 1.0
 */
public class Problem34 {

    // https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
    public int[] searchRange(int[] nums, int target) {
        if (nums == null || nums.length == 0) return new int[]{-1, -1};
        int left = searchLeft(nums, target);
        if (left == -1) return new int[]{-1, -1};
        int right = searchRight(nums, target);
        return new int[]{left, right};
    }

    public int searchLeft(int[] nums, int target) {
        int left = 0, right = nums.length - 1, ans = -1, mid;
        while (left <= right) {
            mid = left + ((right - left) >> 1);
            if (nums[mid] >= target) {
                ans = mid;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        if (ans == -1) return -1;
        return nums[ans] == target ? ans : -1;
    }

    public int searchRight(int[] nums, int target) {
        int left = 0, right = nums.length - 1, ans = -1, mid;
        while (left <= right) {
            mid = left + ((right - left) >> 1);
            if (nums[mid] <= target) {
                ans = mid;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        if (ans == -1) return -1;
        return nums[ans] == target ? ans : -1;
    }
}
